define([
  "jquery",
  "bootstrap",
  "backend",
  "addtabs",
  "table",
  "echarts",
  "echarts-theme",
  "template",
], function (
  $,
  undefined,
  Backend,
  Datatable,
  Table,
  Echarts,
  undefined,
  Template
) {
  var Controller = {
    index: function () {
      // 基于准备好的dom，初始化echarts实例
      var turnoverStatistics = Echarts.init(
        document.getElementById("turnoverStatistics"),
        "walden"
      );
      var userStatistics = Echarts.init(
        document.getElementById("userStatistics"),
        "walden"
      );
      var orderStatistics = Echarts.init(
        document.getElementById("orderStatistics"),
        "walden"
      );
      var salesRanking = Echarts.init(
        document.getElementById("salesRanking"),
        "walden"
      );

      function updateTurnover(col, turnoverdata) {
        // 指定图表的配置项和数据
        var turnoverStatisticsOption = {
          title: {
            text: "营业额统计",
            subtext: "",
            textStyle: {
              color: "#000",
              fontSize: 16,
            },
          },
          color: ["#fdd21b"],
          tooltip: {
            trigger: "axis",
          },
          legend: {
            bottom: "0",
            data: ["营业额(元)"],
          },
          toolbox: {
            show: false,
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: col,
          },
          yAxis: {},
          series: [
            {
              name: "营业额(元)",
              type: "line",
              lineStyle: {
                normal: {
                  width: 1.5,
                },
              },
              data: turnoverdata,
            },
          ],
        };

        turnoverStatistics.setOption(turnoverStatisticsOption);
      }
      function updateUser(col, totaluserlist, newuserlist) {
        var userStatisticsOption = {
          title: {
            text: "用户统计",
            subtext: "",
            textStyle: {
              color: "#000",
              fontSize: 16,
            },
          },
          color: ["#fdd21b", "#fd9090"],
          tooltip: {
            trigger: "axis",
          },
          legend: {
            bottom: "0",
            data: ["用户总量（个）", "新增用户（个）"],
          },
          toolbox: {
            show: false,
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "12%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            data: col,
          },
          yAxis: {
            type: "value",
          },
          series: [
            {
              name: "用户总量（个）",
              type: "line",
            //   stack: "Total",
              data: totaluserlist,
            },
            {
              name: "新增用户（个）",
              type: "line",
            //   stack: "Total",
              data: newuserlist,
            },
          ],
        };
        userStatistics.setOption(userStatisticsOption);
      }
      function updateOrder(col, orderlist, effctorderlist) {
        var orderStatisticsOption = {
          title: {
            text: "订单统计",
            subtext: "",
            textStyle: {
              color: "#000",
              fontSize: 16,
            },
          },
          color: ["#fdd21b", "#fd9090"],
          tooltip: {
            trigger: "axis",
          },
          legend: {
            bottom: "0",
            data: ["订单总数（个）", "有效订单（个）"],
          },
          toolbox: {
            show: false,
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "12%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            data: col,
          },
          yAxis: {
            type: "value",
          },
          series: [
            {
              name: "订单总数（个）",
              type: "line",
            //   stack: "Total",
              data: orderlist,
            },
            {
              name: "有效订单（个）",
              type: "line",
            //   stack: "Total",
              data: effctorderlist,
            },
          ],
        };
        orderStatistics.setOption(orderStatisticsOption);
      }
      function updateSalesRanking(col, toplist) {
        var salesRankingOption = {
          title: {
            text: "销量排名TOP10",
            subtext: "",
            textStyle: {
              color: "#000",
              fontSize: 16,
            },
          },
          color: ["#fdd21b"],
        //   tooltip: {
        //     trigger: "axis",
        //   },
          xAxis: {
            type: "category",
            data: col,
          },
          yAxis: {
            type: "value",
          },
          series: [
            {
              data: toplist,
              type: "bar",
            },
          ],
        };
        salesRanking.setOption(salesRankingOption);
      }

      updateTurnover(Config.turnovercolumn, Config.turnoverdata);
      updateUser(Config.usercolumn, Config.totaluserlist, Config.newuserlist);
      updateOrder(Config.ordercolumn, Config.orderlist, Config.effctorderlist);
      updateSalesRanking(Config.topcolumn, Config.toplist);
      // 使用刚指定的配置项和数据显示图表。
         $(window).resize(function () {
           turnoverStatistics.resize();
           userStatistics.resize();
           orderStatistics.resize();
           salesRanking.resize();
         });

      // $(document).on("click", ".btn-refresh", function () {
      //     setTimeout(function () {
      //         turnoverStatistics.resize();
      //     }, 0);
      // });

      // 监听单选框变化事件
      $('input[name="dateOptions"]').change(function () {
        if ($(this).is(":checked")) {
          const dateRange = $(this).val();

          // 发送AJAX请求
          sendAjaxRequest(dateRange);
        }
      });

      // 发送AJAX请求的函数
      function sendAjaxRequest(dateRange) {
        // 计算日期范围
        const dateParams = calculateDateRange(dateRange);

        // 更新日期范围显示
        //   $("#date-range").text(
        //     `${dateParams.startDate} 至 ${dateParams.endDate}`
        //   );

        userAjaxRequest(dateRange, dateParams);
        turnoverAjaxRequest(dateRange, dateParams);
        ordersAjaxRequest(dateRange, dateParams);
        top10AjaxRequest(dateRange, dateParams);
      }

      // 计算日期范围的函数
      function calculateDateRange(range) {
        const today = new Date();
        let startDate, endDate;

        // 设置结束日期为今天（YYYY-MM-DD格式）
        endDate = formatDate(today);

        switch (range) {
          case "yesterday":
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            startDate = formatDate(yesterday);
            endDate = startDate; // 昨天开始和结束是同一天
            break;

          case "last7days":
            startDate = new Date(today);
            startDate.setDate(startDate.getDate() - 6); // 近7天包含今天，所以减6
            startDate = formatDate(startDate);
            break;

          case "last30days":
            startDate = new Date(today);
            startDate.setDate(startDate.getDate() - 29); // 近30天包含今天，所以减29
            startDate = formatDate(startDate);
            break;

          case "thisWeek":
            startDate = new Date(today);
            // 设置为本周的第一天（周一）
            startDate.setDate(startDate.getDate() - startDate.getDay() + 1);
            startDate = formatDate(startDate);
            break;

          case "thisMonth":
            startDate = new Date(today.getFullYear(), today.getMonth(), 1);
            startDate = formatDate(startDate);
            break;

          default:
            startDate = formatDate(today);
        }

        return { startDate, endDate };
      }

      // 格式化日期为YYYY-MM-DD
      function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
      }

      // 实际AJAX请求示例（注释掉，供参考）
      function userAjaxRequest(dateRange, dateParams) {
        $.ajax({
          url: "report/userStatistics", // 替换为实际API地址
          type: "GET",
          data: {
            begin: dateParams.startDate,
            end: dateParams.endDate,
          },
          success: function (response) {
            if (response.code == 1) {
              var data = response.data;
              updateUser(data.dateList, data.totalUserList, data.newUserList);
            }
          },
          error: function (xhr, status, error) {},
        });
      }
    
        
      function turnoverAjaxRequest(dateRange, dateParams) {
        $.ajax({
          url: "report/turnoverStatistics", // 替换为实际API地址
          type: "GET",
          data: {
            begin: dateParams.startDate,
            end: dateParams.endDate,
          },
          success: function (response) {
            if (response.code == 1) {
              var data = response.data;
              updateTurnover(data.dateList, data.turnoverList);
            }
          },
          error: function (xhr, status, error) {},
        });
      }
      
       function ordersAjaxRequest(dateRange, dateParams) {
        $.ajax({
          url: "report/ordersStatistics", // 替换为实际API地址
          type: "GET",
          data: {
            begin: dateParams.startDate,
            end: dateParams.endDate,
          },
          success: function (response) {
            if (response.code == 1) {
              var data = response.data;
              updateOrder(data.dateList, data.orderCountList,data.validOrderCountList);
            }
          },
          error: function (xhr, status, error) {},
        });
      }
       function top10AjaxRequest(dateRange, dateParams) {
        $.ajax({
          url: "report/top10", // 替换为实际API地址
          type: "GET",
          data: {
            begin: dateParams.startDate,
            end: dateParams.endDate,
          },
          success: function (response) {
            if (response.code == 1) {
              var data = response.data;
              updateSalesRanking(data.nameList, data.numberList);
            }
          },
          error: function (xhr, status, error) {},
        });
      }
    },
  };

  return Controller;
});
